package net.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.kernel.KVisiteur;
import net.ko.framework.Ko;
import net.ko.http.objects.KRequest;
import net.ko.kobject.KObject;
import net.ko.mapping.IMappingControl;

public class Control implements IMappingControl {
	boolean result = false;
	String login;
	String mdp;
	String admin;
	KVisiteur vi;
	
	private String erreur = "";

	@Override
	public boolean isValid(HttpServletRequest request,
			HttpServletResponse response) {
		if (KRequest.keyExists("login", request)) {
			login = KRequest.GETPOST("login", request);
			mdp = KRequest.GETPOST("mdp", request);
			try {
				vi = (KVisiteur) KObject.kloadOne(KVisiteur.class,
						Ko.kdatabase(), "login='" + login + "'");
				if (mdp.equals(vi.getMdp())) {
					request.getSession().setAttribute("user", vi);
					result = true;
				}
			} catch (InstantiationException | IllegalAccessException
					| SQLException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	@Override
	public void onInvalidControl(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			KRequest.forward("fail.do", request, response, "erreur="
					+ erreur);
			return;
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean beforeProcessAction(HttpServletRequest request,
			HttpServletResponse response) {
		return true;
	}

}
